document.addEventListener('mouseup', (e) => {
  const selection = window.getSelection().toString().trim();
  if (selection) {
    showLiveEEButton(e);
  }
});

function showLiveEEButton(e) {
  const existingBtn = document.getElementById('liveee-btn');
  if (existingBtn) existingBtn.remove();

  const btn = document.createElement('div');
  btn.id = 'liveee-btn';
  btn.innerHTML = 'LiveEE';

  const range = window.getSelection().getRangeAt(0);
  const rect = range.getBoundingClientRect();

  Object.assign(btn.style, {
    position: 'absolute',
    left: `${rect.left + window.scrollX}px`,
    top: `${rect.bottom + window.scrollY}px`,
    background: '#4CAF50',
    color: 'white',
    padding: '5px 10px',
    borderRadius: '4px',
    cursor: 'pointer',
    zIndex: 10000
  });

  btn.addEventListener('click', () => {
    const selectedText = window.getSelection().toString();
    const contextParagraph = getContextParagraph(range);
    showPopup(selectedText, contextParagraph);
    btn.remove();
  });

  document.body.appendChild(btn);
}

function getContextParagraph(range) {
  const node = range.startContainer;
  let paragraph = node.textContent || node.parentNode.textContent;
  return paragraph.trim();
}

async function showPopup(selectedText, contextParagraph) {
  const existingPopup = document.getElementById('liveee-popup');
  if (existingPopup) existingPopup.remove();

  const popup = document.createElement('div');
  popup.id = 'liveee-popup';
  popup.innerHTML = '正在获取解释...';

  Object.assign(popup.style, {
    position: 'fixed',
    left: '50%',
    top: '50%',
    transform: 'translate(-50%, -50%)',
    background: 'white',
    color: 'black',
    padding: '20px',
    borderRadius: '8px',
    boxShadow: '0 4px 8px rgba(0,0,0,0.3)',
    zIndex: 10001
  });

  document.body.appendChild(popup);

  // 获取存储的API密钥
  chrome.storage.local.get('deepseekApiKey', async (data) => {
    const apiKey = data.deepseekApiKey;
    if (!apiKey) {
      if (document.body.contains(popup)) {
        popup.innerHTML = '请先在插件设置中配置API密钥。';
      }
      return;
    }

    // 调用DeepSeek API
    try {
      const response = await fetch('https://api.deepseek.com/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: "deepseek-chat",
          messages: [
            { role: "system", content: "你是个英语老师，深入讲解选择部分的文本在上下文中的解释，从三个方面解释：\n1.选择部分的内容是词组吗\n2.它的原本含义是什么，在句子中我怎么理解它\n3.这句话怎么翻译" },
            { role: "user", content: `<select>\n${selectedText}\n</select>\n<context>\n${contextParagraph}\n</context>` }
          ],
          stream: false
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      console.log('API响应数据:', data); // 打印完整的API响应数据

      // 检查响应结构
      if (data.choices && data.choices.length > 0 && data.choices[0].message) {
        const explanation = data.choices[0].message.content;

        // 确保弹窗仍然存在
        if (document.body.contains(popup)) {
          // 流式输出
          let index = 0;
          const interval = setInterval(() => {
            if (index < explanation.length) {
              popup.innerHTML += explanation[index++];
            } else {
              clearInterval(interval);
            }
          }, 50);
        }
      } else {
        console.error('API响应格式不正确:', data);
        throw new Error('API响应格式不正确');
      }

    } catch (error) {
      console.error('API调用失败:', error);
      if (document.body.contains(popup)) {
        popup.innerHTML = '获取解释失败，请重试。';
      }
    }
  });

  // 点击弹窗外部关闭弹窗
  document.addEventListener('click', function closePopup(e) {
    if (!popup.contains(e.target) && e.target.id !== 'liveee-btn') {
      popup.remove();
      document.removeEventListener('click', closePopup);
    }
  });
} 